<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>contextmenu</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.css"
        integrity="sha256-rQq4Fxpq3LlPQ8yP11i6Z2lAo82b6ACDgd35CKyNEBw=" crossorigin="anonymous"/>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.js"
          integrity="sha256-77IKwU93jwIX7zmgEBfYGHcmeO0Fx2MoWB/ooh9QkBA="
          crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
  <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
          integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
          crossorigin="anonymous"></script>

  <style type="text/css">
    .contextmenu {
      position: absolute;
      top: 100%;
      width: 120px;
      height: auto;
      z-index: 9;
      background-color: #ffd35f;
    }

    .contextmenu ul {
      width: 100%;
      padding: 6px 2px 0 2px;
      list-style: none;
    }

    .contextmenu > ul > li {
      width: 100%;
      text-align: center;
      padding: 5px 0;
    }

    .contextmenu > ul > li:hover {
      background-color: rgba(255, 0, 0, 0.5);
    }
  </style>

</head>
<body style="margin:0 0 0 0; padding:0 0 0 0;">
<div id="contextmenu_container" class="contextmenu">
  <ul>
    <li><a href="#">菜单1</a></li>
    <li><a href="#">菜单2</a></li>
    <li><a href="#">菜单3</a></li>
  </ul>
</div>

<div id="map"></div>


<script type="text/javascript">
  var gaodeMapLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
      url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
    })
  });
  var map = new ol.Map({
    layers: [gaodeMapLayer],
    view: new ol.View({
      center: [120,30],
      projection: 'EPSG:4326',
      zoom: 10
    }),
    target: 'map'
  });  var menu_overlay = new ol.Overlay({
    element: document.getElementById("contextmenu_container"),
    positioning: 'center-center'
  });

  menu_overlay.setMap(map);

  $(map.getViewport()).on("contextmenu", function (e) {
    e.preventDefault();
    var coordinate = map.getEventCoordinate(e);
    menu_overlay.setPosition(coordinate);
  });
  $(map.getViewport()).on("click", function (e) {
    e.preventDefault();
    menu_overlay.setPosition(undefined);
  });
</script>
</body>
</html>
